<style lang="less">
     @import './index.less';
</style>

<template>
  <div>
    <Card>
      <Row class="margin-bottom-10">
        <i-col span="20" class="margin-bottom-5">
          <div v-show="!searchList" style="display:inline-flex">
              <Input class="margin-right-5" size="small" placeholder="联系人" v-model="contact_name" style="width: 200px"></Input>
              <Select placeholder="客户名称" clearable filterable v-model="customer_name" size="small" class="margin-right-5" style="width: 200px">
                <Option v-for="item in companyList" :value="item.customer_name" :key="item.customer_id">{{item.customer_name}}</Option>
              </Select>
              <Button class="margin-right-5" type="primary" size="small" icon="ios-search" @click="search">搜索</Button>
              <Button class="margin-right-5" type="primary" size="small" @click="showSearch" icon="arrow-up-b">收起</Button>
          </div>
          <div v-show="searchList">
            <Input placeholder="联系人" size="small" style="width: 200px" v-model="contact_name"></Input>
            <Button class="margin-right-5" type="primary" size="small" icon="ios-search" @click="search">搜索</Button>
            <Button type="primary" size="small" icon="arrow-down-b" @click="showSearch">高级搜索</Button>
          </div>
        </i-col>
        <i-col span="4">
            <add-btn class="pull-right" @addclick="addCustomerHandle"></add-btn>
        </i-col>
      </Row>
      <Row :gutter="10">
            <i-col span="17">
              <Table highlight-row :columns="columns1" :data="contactsList.data" @on-current-change="getCurrentRow"></Table>
              <Page :current="currentPage" :total="contactsList.totalCount" :page-size="pageSize" show-total @on-change="changePage"></Page>
            </i-col>
            <i-col span="7">
              <Card dis-hover v-show="tableCurrentRowInfo.customer_name">
                <p slot="title">{{tableCurrentRowInfo.customer_name}}--{{tableCurrentRowInfo.contact_name}}</p>
                <Tabs>
                  <TabPane label="拜访记录">
                    <Button type="dashed" class="margin-bottom-10" long @click="addVisitHandle" :disabled="tableCurrentRowInfo.creator !== userName">添加追踪记录</Button>
                    <Card dis-hover class="margin-bottom-10" v-for="item in visitList" :key="item.visit_id">
                      <p>拜访时间：{{item.visit_date}}</p>
                      <p>拜访情况：{{item.result}}</p>
                      <p>解决办法：{{item.solution}}</p>
                      <p>目前进展：{{item.goal}}</p>
                      <p>实际进展：{{item.progress}}</p>
                    </Card>
                  </TabPane>
                  <TabPane label="销售机会">
                    <Button type="dashed" class="margin-bottom-10" long @click="addChanceHandle" :disabled="tableCurrentRowInfo.creator !== userName">添加销售机会</Button>
                    <Card dis-hover class="margin-bottom-10" v-for="item in chanceList" :key="item.chance_id">
                      <p>预计签单时间：{{item.predict_sign_date}}</p>                      
                      <p>合作需求：{{item.demand}}</p>
                      <p>迫切程度：{{item.level}}</p>
                      <p>预计销售金额：{{item.predict_amount}}</p>
                      <p>销售阶段：{{item.period}}</p>
                      <p>需要支援：{{item.assist}}</p>
                      <p>其他风险点：{{item.risk}}</p>
                    </Card>
                  </TabPane>
                </Tabs>
              </Card>
            </i-col>
          </Row>
    </Card>
    <Modal width="1000"
      :loading="modalLoading"
      v-model="modalControl"
      :title="modalTitle"
      :ok-text="okText"
      @on-ok="contactModalSubmit('contactFormRef')"
      @on-cancel="contactModalCancel('contactFormRef')">
      <Form :model="contactForm" ref="contactFormRef" :rules="ruleValidate" label-position="right" :label-width="80" style="width:94%">
          <Row :gutter="10">
            <i-col span="11" offset="1">
              <FormItem label="企业名称" prop="customer_id">
                <Select v-model="contactForm.customer_id">
                  <Option v-for="item in companyList" :value="item.customer_id" :key="item.customer_id">{{item.customer_name}}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="11">
              <FormItem label="合作部门">
                <Input type="text" v-model="contactForm.org"></Input>
            </FormItem>
            </i-col>
          </Row>
          <Row :gutter="10">
            <i-col span="11" offset="1">
              <FormItem label="联系人" prop="contact_name">
                <Input type="text" v-model="contactForm.contact_name"></Input>
                <Checkbox v-model="contactForm.ismanager">是否为拍板人</Checkbox>
              </FormItem>
            </i-col>
            <i-col span="11">
              <FormItem label="电话">
                <Input type="text" v-model="contactForm.phone"></Input>
            </FormItem>
            </i-col>
          </Row>
          <Row :gutter="10">
            <i-col span="11" offset="1">
              <FormItem label="职务">
                <Input type="text" v-model="contactForm.position"></Input>
              </FormItem>
            </i-col>
            <i-col span="11">
              <FormItem label="负责事项">
                <Input type="text" v-model="contactForm.responsibility"></Input>
            </FormItem>
            </i-col>
          </Row>
          <Row :gutter="10">
            <i-col span="11" offset="1">
              <FormItem label="邮箱">
                <Input type="text" v-model="contactForm.e_mail"></Input>
              </FormItem>
            </i-col>
            <i-col span="11">
              <FormItem label="联系地址">
                <Input type="text" v-model="contactForm.address"></Input>
            </FormItem>
            </i-col>
          </Row>
        </Form>
    </Modal>
    <Modal v-model="visitModal" title="添加追踪记录" width="800" ok-text="保存" @on-ok="createVisit" @on-cancel="cancel">
      <Row>
        <i-col span="16" offset="4">
          <Form :model="visitForm" label-position="right" :label-width="80">
              <FormItem label="拜访时间">
                <DatePicker type="date" ref="visitDatePicker" format="yyyy-MM-dd" style="width: 431px" v-model="visitForm.visit_date"></DatePicker>
              </FormItem>
              <FormItem label="拜访情况">
                  <Input type="textarea" v-model="visitForm.result"></Input>
              </FormItem>
              <FormItem label="解决办法">
                  <Input type="textarea" v-model="visitForm.solution"></Input>
              </FormItem>
              <FormItem label="目前进展">
                  <Input type="textarea" v-model="visitForm.goal"></Input>
              </FormItem>
              <FormItem label="实际进展">
                  <Input type="textarea" v-model="visitForm.progress"></Input>
              </FormItem>
          </Form>
        </i-col>
      </Row>
    </Modal>
    <Modal v-model="addChanceModal" title="添加销售机会" width="800" @on-ok="createChance" @on-cancel="cancel">
      <Row>
        <i-col span="16" offset="4">
          <Form :model="addChanceForm" label-position="right" :label-width="100">
              <FormItem label="合作需求">
                  <Input type="text" v-model="addChanceForm.demand"></Input>
              </FormItem>
              <FormItem label="迫切程度">
                  <Select v-model="addChanceForm.level">
                    <Option value="一般">一般</Option>
                    <Option value="紧急">紧急</Option>
                </Select>
              </FormItem>
              <FormItem label="预计销售金额">
                  <Input type="text" v-model="addChanceForm.predict_amount"></Input>
              </FormItem>
              <FormItem label="预计签单时间">
                <DatePicker type="date" ref="chanceDatePicker" format="yyyy-MM-dd" style="width: 412px" v-model="addChanceForm.predict_sign_date"></DatePicker>
              </FormItem>
              <FormItem label="销售阶段">
                  <Input type="text" v-model="addChanceForm.period"></Input>
              </FormItem>
              <FormItem label="需要支援">
                  <Input type="text" v-model="addChanceForm.assist"></Input>
              </FormItem>
              <FormItem label="其他风险点">
                  <Input type="text" v-model="addChanceForm.risk"></Input>
              </FormItem>
          </Form>
        </i-col>
      </Row>
    </Modal>
  </div>
</template>

<script>

import addBtn from './component/access-add-button.vue';
import deleteBtn from './component/access-delete-button.vue';
import modifyBtn from './component/access-modify-button.vue';
import expandRow from './component/table-expand.vue';
import moment from 'moment';

export default {
  data() {
    return {
      modalLoading:true,
      modalControl:false,
      modalTitle:'',
      okText:'',
      contactForm:{
        ismanager:false
      },
      userName:'',
      searchList:true,
      loading:true,
      tableCurrentRowInfo:{},
      companyList:[],
      contactsList:[],
      visitList:[],
      chanceList:[],
      showCustomerModal:false,
      visitModal:false,
      visitForm:{},
      addChanceModal:false,
      addChanceForm:{},
      customer_name:'',
      contact_name:'',
      pageSize:15,
      currentPage:1,
      columns1:[
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h(expandRow, {
                props: {
                    row: params.row
                }
            })
          }
        },
        {
          title: '联系人',
          key: 'contact_name',
          align:'center'
        },
        {
          title: '所在公司',
          key: 'customer_name',
          align:'center'
        },
        {
          title: '合作部门',
          key: 'org',
          align:'center'
        },
        {
          title: '客户经理',
          key: 'employee_name',
          align:'center'
        },
        {
          title: '联系电话',
          key: 'phone',
          align:'center'
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
              return h('div', [
                h('Tooltip', {
                  props: {
                    placement: 'top',
                    content: '详细信息'
                  }
                }, [h('Button', {
                  props: {
                    size: 'small',
                    icon: 'qr-scanner',
                    type: 'text'
                  },
                  on: {
                    click: () => {
                      this.$router.push({
                        name:'customer_customer-mgt-detail',
                        params:{id:params.row.contact_id}
                      })
                    }
                  }
                })]),
                h('Tooltip', {
                  props: {
                    placement: 'top',
                    content: '编辑'
                  },
                }, [h(modifyBtn, {
                  props:{
                    creator:params.row.creator
                  },
                  on: {
                    modifyClick: () => {
                      this.modify(params.row);
                    }
                  }
                }
                )]),
                h('Tooltip', {
                  props: {
                    placement: 'top',
                    content: '删除'
                  }
                }, [h(deleteBtn, {
                  props:{
                    creator:params.row.creator
                  },
                  on: {
                    delclick: () => {
                      this.$Modal.confirm({
                        title: '确认',
                        content: '确认要删除联系人【' + params.row.contact_name + '】吗？',
                        onOk: () => {
                          this.remove(params.row.contact_id);
                        }
                      });
                    }
                  }
                })])
              ]);
            }
        }
      ],
      ruleValidate:{
        customer_id:[
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        contact_name:[
          { required: true, message: '请填写联系人姓名', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    getCompanyList() {
      this.$http.get('/customer/customers').then((res) => {
        this.companyList = res.data.returnValue
      })
    },
    getVisits(contact_id) {
      this.$http.get('/customer/contact/'+ contact_id  +'/visits').then((res) => {
        this.visitList = res.data.returnValue.map(item => { 
          item.visit_date ? item.visit_date = moment(item.visit_date).format('YYYY-MM-DD') : item.visit_date = ''
          return item
        })
      })
    },
    getChances(contact_id) {
      this.$http.get('/customer/contact/'+ contact_id  +'/chances').then((res) => {
        this.chanceList = res.data.returnValue.map(item => {
          item.predict_sign_date ? item.predict_sign_date = moment(item.predict_sign_date).format('YYYY-MM-DD') : item.predict_sign_date =''
          return item
        })
      })
    },
    getContacts() {
      this.$http.get('/customer/contacts/page?customer_name='+this.customer_name+'&contact_name='+this.contact_name+'&pageSize='+this.pageSize+'&currentPage='+this.currentPage).then((res) => {
        this.contactsList = res.data.returnValue
        // 设置默认选中以及显示对应的拜访记录和销售机会
        this.contactsList.data[0]._highlight = true
        this.tableCurrentRowInfo = this.contactsList.data[0]
        this.getVisits(this.tableCurrentRowInfo.contact_id)
        this.getChances(this.tableCurrentRowInfo.contact_id)
      })
    },
    getCurrentRow(currentRow) {
      this.tableCurrentRowInfo = currentRow
      this.getVisits(this.tableCurrentRowInfo.contact_id)
      this.getChances(this.tableCurrentRowInfo.contact_id)
    },
    addCustomerHandle() {
      this.getCompanyList()
      this.modalTitle = '添加联系人'
      this.okText = '确定'
      this.modalControl = true
    },
    contactModalCancel(name) {
      this.contactForm = {}
      this.$refs[name].resetFields();
    },
    contactModalSubmit(name) {
      this.$refs[name].validate((valid) => {
        if(valid){
          if(!this.contactForm.contact_id) {
            this.$http.post('/customer/contact',this.contactForm).then((res) => {
            this.$Message.success('我的客户添加成功')
            this.modalControl = false
            this.contactForm = {}
            this.getContacts()
            }).catch(() => {
              this.$Message.error('添加失败，请稍后重试！')
            })
          }else {
            this.$http.put('/customer/contact',this.contactForm).then((res) => {
              this.$Message.success(res.data.message)
              this.modalControl = false
              this.contactForm = {}
              this.getContacts()
            }).catch(() => {
              this.$Message.error('修改失败，请重试')
            })
          }
        }else {
          this.reloading()
        }
      })
    },
    reloading() {
      this.modalLoading = false
      this.$nextTick(() => {
        this.modalLoading = true
      })
    },
    addVisitHandle() {
      this.visitModal = true
    },
    createVisit() {
      this.visitForm.contact_id = this.tableCurrentRowInfo.contact_id
      this.$http.post('/customer/visit',this.visitForm).then((res) => {
        this.$Message.success(res.data.message)
        this.$refs.visitDatePicker.handleClear()
        this.getVisits(this.tableCurrentRowInfo.contact_id)
        this.visitForm = {}
      }).catch(() => {
        this.$Message.error('拜访记录添加失败，请稍后重试！')
      })
    },
    addChanceHandle() {
      this.addChanceModal = true
    },
    createChance() {
      this.addChanceForm.org = this.tableCurrentRowInfo.org
      this.addChanceForm.customer_id = this.tableCurrentRowInfo.customer_id
      this.addChanceForm.contact_id = this.tableCurrentRowInfo.contact_id
      this.$http.post('/customer/chance',this.addChanceForm).then((res) => {
        this.$Message.success(res.data.message)
        this.$refs.chanceDatePicker.handleClear()
        this.getChances(this.tableCurrentRowInfo.contact_id)
        this.addChanceForm = {}
      }).catch(() => {
        this.$Message.error('销售添加失败，请稍后重试！')
      })
    },
    cancel() {
      this.addCustomerForm = {}
      this.$refs.visitDatePicker.handleClear()
      this.$refs.chanceDatePicker.handleClear()
      this.$refs['addCustomerForm'].resetFields();
      this.visitForm = {}
      this.addChanceForm = {}
    },
    modify(info) {
      this.getCompanyList()
      this.contactForm = _.cloneDeep(info)
      this.modalTitle = '修改联系人'
      this.okText = '保存'
      this.modalControl = true
    },
    remove(id) {
      this.$http.delete('/customer/contact/' + id).then((res) => {
        this.$Message.success('删除成功！')
        this.getContacts()
      }).catch(() => {
        this.$Message.error('删除失败，请重试！')
      })
    },
    // show(rowData) {
    //   this.$router.push({
    //     name:'customer_customer-mgt-detail',
    //     query:rowData
    //   })
    // },
    changePage(page) {
      this.currentPage = page
      this.getContacts()
    },
    search(){
      this.getContacts()
    },
    showSearch() {
      this.searchList = !this.searchList
      this.contact_name = ''
      this.customer_name = ''
      this.getContacts()
    }
  },
  components: {
    addBtn,
    deleteBtn,
    modifyBtn
  },
  mounted() {
    this.getContacts()
    this.getCompanyList()
    this.userName = this.$auth.user().name
  }
}
</script>

